package com.dsprun.dspai.controller;

import com.dsprun.dspai.dto.*;
import com.dsprun.dspai.model.CodeGenerationResponse;
import com.dsprun.dspai.model.DocumentResponse;
import com.dsprun.dspai.model.Person;
import com.dsprun.dspai.model.Sentiment;
import com.dsprun.dspai.services.AiService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;

import java.util.List;

/**
 * AI服务控制器，提供RESTful API接口
 */
@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
@Tag(name = "AI服务", description = "提供各种AI功能接口，包括聊天、文档处理、代码生成等")
public class AiController {

    private final AiService aiService;


    @Operation(
            summary = "简单聊天",
            description = "提供基本的AI聊天功能，接收用户消息并返回AI响应",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功获取AI响应",
                            content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class))
                    )
            }
    )
    @PostMapping("/chat")
    @ResponseBody // 直接返回字符串内容，不解析为模板
    public String chat(@RequestBody ChatRequest request) {
        return aiService.chat(request.getMessage());
    }

    @Operation(
            summary = "流式聊天",
            description = "提供流式AI聊天功能，以Server-Sent Events形式返回响应",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功获取AI响应流",
                            content = @Content(mediaType = "text/event-stream", schema = @Schema(implementation = String.class))
                    )
            }
    )
    @PostMapping(value = "/chat-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public Flux<String> chatStream(@RequestBody ChatRequest request) {
        return aiService.chatStream(request.getMessage());
    }

    @Operation(
            summary = "带记忆的聊天",
            description = "提供带有会话记忆的AI聊天功能，需要提供会话ID",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功获取AI响应",
                            content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class))
                    )
            }
    )
    @PostMapping("/chat-with-memory")
    @ResponseBody
    public String chatWithMemory(@RequestBody ChatRequest request) {
        return aiService.chatWithMemory(request.getMessage(), request.getConversationId());
    }
    @PostMapping(value = "/chat-stream-memory", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @Operation(
            summary = "带记忆的流式聊天",
            description = "保持对话上下文的流式响应",
            responses = {
                    @ApiResponse(
                            description = "SSE流式响应",
                            content = @Content(mediaType = "text/event-stream")
                    )
            }
    )
    public Flux<String> chatStreamWithMemory(
            @Parameter(description = "带会话ID的聊天请求", required = true)
            @RequestBody ChatMemoryRequest request) {

        return aiService.chatWithMemoryStream(
                request.getMessage(),
                request.getConversationId()
        );
    }


    // 请求类
    @Data
    static class ChatMemoryRequest {
        @Schema(description = "消息内容", example = "讲个笑话", required = true)
        private String message;

        @Schema(description = "会话ID", example = "conv_123", required = true)
        private String conversationId;
    }

    @Operation(
            summary = "信息提取",
            description = "从文本中提取结构化个人信息",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功提取信息",
                            content = @Content(mediaType = "application/json", schema = @Schema(implementation = Person.class))
                    )
            }
    )
    @PostMapping("/extract-info")
    @ResponseBody // 直接返回字符串内容，不解析为模板
    public Person extractInfo(@RequestBody ExtractInfoRequest request) {
        return aiService.extractInfo(request.getText());
    }

    @Operation(
            summary = "情感分析",
            description = "分析文本的情感倾向",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功分析情感",
                            content = @Content(mediaType = "application/json", schema = @Schema(implementation = Sentiment.class))
                    )
            }
    )
    @PostMapping("/analyze-sentiment")
    @ResponseBody // 直接返回字符串内容，不解析为模板
    public Sentiment analyzeSentiment(@RequestBody AnalyzeSentimentRequest request) {
        return aiService.analyzeSentiment(request.getText());
    }

    @Operation(
            summary = "生成摘要",
            description = "为输入文本生成简洁摘要",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功生成摘要",
                            content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class))
                    )
            }
    )
    @PostMapping("/generate-summary")
    @ResponseBody // 直接返回字符串内容，不解析为模板
    public String generateSummary(@RequestBody SummaryRequest request) {
        return aiService.generateSummary(request.getText(), request.getMaxLength());
    }

    @Operation(
            summary = "加载文档",
            description = "上传并处理文档，以便后续进行文档问答",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功加载文档",
                            content = @Content(mediaType = "application/json", schema = @Schema(implementation = DocumentResponse.class))
                    )
            }
    )
    @PostMapping("/load-document")
    @ResponseBody // 直接返回字符串内容，不解析为模板
    public DocumentResponse loadDocument(
            @Parameter(description = "待上传的文档文件", required = true,
                    content = @Content(mediaType = MediaType.MULTIPART_FORM_DATA_VALUE))
            @RequestParam("file") MultipartFile file) {
        return aiService.loadDocument(file);
    }

    @Operation(
            summary = "文档问答",
            description = "基于已加载的文档进行问答",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功获取回答",
                            content = @Content(mediaType = "text/plain", schema = @Schema(implementation = String.class))
                    )
            }
    )
    @PostMapping("/ask-document")
    @ResponseBody // 直接返回字符串内容，不解析为模板
    public String askDocument(@RequestBody AskDocumentRequest request) {
        return aiService.askDocument(request.getQuestion(), request.getDocumentId());
    }

    @Operation(
            summary = "获取文档列表",
            description = "获取所有已加载文档的信息列表",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功获取文档列表",
                            content = @Content(mediaType = "application/json",
                                    schema = @Schema(implementation = DocumentResponse.class, type = "array")))
            }
    )
    @GetMapping("/documents")
    public List<DocumentResponse> listDocuments() {
        return aiService.listDocuments();
        }

    @Operation(
            summary = "翻译",
            description = "将文本翻译为目标语言",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功翻译文本",
                            content = @Content(mediaType = "application/json", schema = @Schema(implementation = String.class))
                    )
            }
    )
    @PostMapping("/translate")
    @ResponseBody // 直接返回字符串内容，不解析为模板
    public String translate(@RequestBody TranslationRequest request) {
            return aiService.translate(request.getText(), request.getTargetLanguage());
    }

    @Operation(
            summary = "代码生成",
            description = "根据功能描述生成代码",
            responses = {
                    @ApiResponse(
                            responseCode = "200",
                            description = "成功生成代码",
                            content = @Content(mediaType = "application/json", schema = @Schema(implementation = CodeGenerationResponse.class))
                    ),
                    @ApiResponse(
                            responseCode = "400",
                            description = "无效的请求参数"
                    )
            }
    )
    @PostMapping("/generate-code")
    public CodeGenerationResponse generateCode(
    @Valid @RequestBody CodeGenerationRequest request) {

            long startTime = System.currentTimeMillis();
            CodeGenerationResponse response = aiService.generateCode(
            request.getDescription(),
            request.getLanguage(),
            request.getStyle(),
            request.isIncludeComments(),
            request.getLibraries(),
            request.getComplexityLevel(),
            request.isIncludeTests()
            );

            response.setProcessingTimeMs(System.currentTimeMillis() - startTime);
            return response;
            }
        }